import { Dialog, Notify } from 'quasar';

/**
 * Confirm popup
 * @param message
 * @returns
 */
export function confirm(message) {
  return Dialog.create({
    title: 'Confirm',
    message: message,
    cancel: true,
    persistent: true
  })
}

/**
 * Notify popup
 * @param message
 * @param color
 * @param timeout
 * @param position
 * @returns
 */
export function notify(message, color = 'positive', timeout = 5000, position = 'bottom-right') {
  switch (color) {
    case 'positive':
      console.debug(message)
      break
    case 'info':
      console.info(message)
      break
    case 'negative':
      console.error(message)
      break
    case 'warning':
      console.warn(message)
      break
    default:
      console.log(message)
      break
  }
  return Notify.create({
    message: message,
    color: color,
    position: position,
    timeout: timeout,
    closeBtn: timeout === 0 ? 'Dismiss' : false
  })
}

/**
 * Prompt popup
 * @param title
 * @param message
 * @param defaultValue of input
 * @param type of input
 * @returns
 */
export function prompt(title, message, defaultValue, type = 'text') {
  return Dialog.create({
    title: title,
    message: message,
    prompt: {
      model: defaultValue,
      type: type
    },
    cancel: true,
    persistent: true
  })
}

/**
 * Read text file
 * @param pathname
 * @returns {Promise}
 */
export function readFile(pathname) {
  return new Promise(function (resolve, reject) {
    fetch(pathname)
      .then((res) => {
        if (!res.ok) reject(`${pathname}: ${res.statusText} (${res.status})`)
        return res.text()
      })
      .then((text) => {
        resolve(text)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

/**
 * Import a json file
 * @returns {Promise}
 */
export function importFile() {
  return new Promise(function (resolve, reject) {
    const dialog = document.createElement('input')
    dialog.type = 'file'
    dialog.accept = 'application/json'
    dialog.onchange = (e) => {
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.onload = (readerEvent) => {
        resolve(readerEvent.target.result)
      }
      reader.readAsText(file, 'UTF-8')
    }
    dialog.click()
  })
}

/**
 * Import a video file
 * @returns {Promise}
 */
export function importVideo() {
  return new Promise(function (resolve, reject) {
    const dialog = document.createElement('input')
    dialog.type = 'file'
    dialog.accept = 'video/*'
    dialog.onchange = (e) => {
      const file = e.target.files[0]
      resolve({
        filename: file.name,
        type: file.type.split('/').at(-1),
        videoSrc: URL.createObjectURL(file)
      })
    }
    dialog.click()
  })
}

/**
 * Convert time to index
 * @param state
 * @param time
 * @returns {number}
 */
export function time2index(fps, time) {
  return Math.round(fps * time)
}

/**
 * Convert index to time
 * @param state
 * @param index
 * @returns {number}
 */
export function index2time(fps, index) {
  return parseFloat((index / fps).toFixed(3))
}

/**
 * Convert a number to fixed 2 format
 * @param value
 * @returns {string}
 */
export function toFixed2(value) {
  if (value) {
    return value.toFixed(2)
  } else {
    return '0.00'
  }
}

/**
 * Generate a random color
 * @returns {string}
 */
export function randomColor() {
  return `#${('000000' + ((Math.random() * 16777216) | 0).toString(16)).slice(-6)}`
}

function clean(link) {
  // allow time for iOS
  setTimeout(() => {
    window.URL.revokeObjectURL(link.href)
  }, 10000)

  link.remove()
}

export function exportFile(filename, rawData, opts = {}) {
  const { mimeType, byteOrderMark, encoding } = typeof opts === 'string'
    ? { mimeType: opts }
    : opts

  const data = encoding !== void 0
    ? (new TextEncoder(encoding)).encode([ rawData ])
    : rawData

  const blobData = byteOrderMark !== void 0 ? [ byteOrderMark, data ] : [ data ]
  const blob = new Blob(blobData, { type: mimeType || 'application/octet-stream' })
  const link = document.createElement('a')

  link.href = window.URL.createObjectURL(blob)
  link.setAttribute('download', filename)

  // Check for "download" attribute support;
  // If not supported, open this in new window
  if (typeof link.download === 'undefined') {
    link.setAttribute('target', '_blank')
  }

  link.classList.add('hidden')
  link.style.position = 'fixed' // avoid scrolling to bottom
  document.body.appendChild(link)

  try {
    link.click()
    clean(link)
    return true
  }
  catch (err) {
    clean(link)
    return err
  }
}
